﻿using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

[Serializable]
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(Format.UserDefined, IsInvariantToDuplicates=false, IsInvariantToOrder=false, IsInvariantToNulls=true, MaxByteSize=-1)]
public struct JoinStrings : IBinarySerialize
{
    private char[] sb;
    private int pos;
    public void Init()
    {
        sb = new char[512000];
        pos = 0;
    }

    public void Accumulate(SqlString Value)
    {
        if (Value.IsNull) return;
        char[] src = Value.ToString().ToCharArray();
        Array.Copy(src, 0, sb, pos, src.Length);
        pos += src.Length;
        sb[pos] = ',';
        pos++;
    }

    public void Merge(JoinStrings Group)
    {
        Accumulate(Group.Terminate());
    }

    public SqlString Terminate()
    {
        if (pos <= 0)
            return new SqlString();
        else
        {
            //KG: Sıralı getirmesi için ekledim.
            string result = new String(sb, 0, pos - 1);
            string[] values = result.Split(',');
            int[] iValues = new int[values.Length];
            for (int i = 0; i < values.Length; i++)
            {
                iValues[i] = Convert.ToInt32(values[i]);
            }
            Array.Sort(iValues);

            string sortedResult = "";
            for (int i = 0; i < iValues.Length; i++)
            {
                sortedResult += iValues[i].ToString() + ",";
            }
            sortedResult = sortedResult.Substring(0, sortedResult.Length - 1);
            return new SqlString(sortedResult);
        }
           
    }

    public void Read(System.IO.BinaryReader r)
    {
        this.Init();
        pos = r.ReadInt32();
        r.Read(sb, 0, pos);
    }

    public void Write(System.IO.BinaryWriter w)
    {
        w.Write(pos);
        w.Write(sb, 0, pos);
    }
}